import getIn from '../../../../yali-sdk/utils/getIn';
import { SUCCESS } from '../../../../yali-sdk/utils/success';
import { FAIL } from '../../../../yali-sdk/utils/fail';
import { getImagePath, showFail, showSuccess } from '../../../config/common';
import cateringProductDetail from '../../../../yali-sdk/business/catering/cateringProductDetail';
import getGoodsCartQuery from '../../../../yali-sdk/business/catering/getGoodsCartQuery';
import cartDetailQuery from '../../../../yali-sdk/business/catering/cartDetailQuery';
import cartEmptyQuery from '../../../../yali-sdk/business/catering/cartEmptyQuery';
import { getLocalTime } from '../../../../yali-sdk/business/coupon/common';
import { SHIPPING_CART_PATH, CATERING_CREAT_ORDER } from '../../pathUrl';
import { checkLogin } from '../../../../yali-sdk/utils/wxLogin';
import { removeNotifier, addNotifier, notify } from '../../../../yali-sdk/utils/NotifyRegistryCenter';
import { payDescText } from '../../../../yali-sdk/business/catering/constrants';
const pageConfig = {
  data: {
    productObject: undefined, // 产品详情数据
    imageArray: [], // 图集
    indicatorDots: true,
    autoplay: true,
    scrollHeight: getIn(getApp(), ['globalData', 'window_height']) - 50,
    showCouponWin: false, // 优惠券列表弹窗
    couponParams: {},
    fullReductionActivity: undefined,
    totalPrice: 0,// 总价格
    totalCount: 0, // 总商品数
    carArray: [],
    dispatch_limit: 0,//起送价格
    payDesc: '去结算', // 右下角结算文字
    deliveryPrice: 0,//配送費
    fold: false,// 购物车开关
    selectPro: false, // 属性窗口
    detailShow: false, // 酒店费用明细开关
    isScrollY: true,
  },
  onLoad(options) {
    /** 获取产品详情 */
    wx.showLoading();
    this.fetchData();
    this.fetchCart();
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: options.color,
    });
    this.setData({ color: options.color, template: Number(options.template) })
  },
  onReady() {
    // addNotifier && addNotifier('updateToken', () => this.onLoad(), this);
  },
  onUnload() {
    // removeNotifier('updateToken');
    notify && notify('UPDATE_GOODDLIST_DATA')
  },
  pressSwiperImage(e) {
    const current = getIn(e, ['currentTarget', 'dataset', 'image']);
    const urls = getIn(e, ['currentTarget', 'dataset', 'imagearray']);
    wx.previewImage({
      current, // 当前显示图片的http链接
      urls, // 需要预览的图片http链接列表
    });
  },
  show(key) {
    this.setData({
      [key]: true, isScrollY: false,
    });
  },
  /** 弹出优惠券* */
  showCouponWin() {
    this.show('showCouponWin');
  },
  /** 关闭优惠券窗口回调* */
  hideCouponCallBack(e) {
    this.setData({ showCouponWin: e.detail.showCouponWin, isScrollY: true });
  },
  //弹起购物车
  toggleList() {
    if (this.data.totalCount > 0) {
      this.show('fold');
    }
  },
  // 关闭购物车
  hideCartCallBack(e) {
    this.setData({ ...e.detail, isScrollY: true });
  },
  // 产品数据
  fetchData() {
    const id = getIn(this.options, ['id']);
    const shop_id = getIn(this.options, ['shop_id']);
    const token = getIn(getApp(), ['globalData', 'token']);
    global.ActionDispatcher.execute(cateringProductDetail, { token, id, shop_id }, (status, result) => {
      if (status == SUCCESS && result) {
        const productObject = getIn(result, ['data']);
        let fullReductionActivity;
        // 参加了活动
        if (getIn(productObject, ['activity', 'length']) > 0) {
          // 秒杀和限时一定是第一个 如果不存在代表没有参加这两个活动
          productObject.activity && productObject.activity.map && productObject.activity.map((ac) => {
            if (ac.reduce_type == 3) {
              fullReductionActivity = ac;
              this.setData({ fullReductionActivity })
            }
          });
        }
        /** 图片处理 */
        let pro_pics = [];
        getIn(productObject, ['pictures']) && getIn(productObject, ['pictures']).map && getIn(productObject, ['pictures']).map(img => { pro_pics.push(img.picture_url) });
        /** 如果没有图集 就默认是索引图 */
        const imageArray = getIn(productObject, ['pictures', 'length']) > 0 ?
          pro_pics : [getIn(productObject, ['cover_picture'])];
        // 处理html
        const content = getIn(result, ['data', 'mobile_content']);
        const couponParams = { product_id: getIn(productObject, ['id']), rows: 10, page: 1 };
        wx.hideLoading();
        this.setData({
          productObject, imageArray, couponParams
        });
      } else if (status == FAIL) {
        wx.hideLoading();
        showFail((result && result.msg) || '详情获取失败');
      }
    });
  },
  // 购物车数据
  fetchCart() {
    const token = getIn(getApp(), ['globalData', 'token']);
    const shop_id = getIn(this.options, ['shop_id']);
    global.ActionDispatcher.execute(cartDetailQuery, { token, shop_id }, (code, res) => {
      if (code == SUCCESS) {
        const carArray = getIn(res.data, ['list']) || [];
        const totalPrice = getIn(res.data, ['total_price']) || 0;
        const totalCount = getIn(res.data, ['total_num']) || 0;
        const dispatch_fee = getIn(res.data, ['config', 'dispatch_fee']) || 0;
        const dispatch_limit = getIn(res.data, ['config', 'dispatch_limit']);
        const payDesc = payDescText(totalPrice, dispatch_limit);
        this.setData({ carArray, totalPrice: totalPrice, totalCount, dispatch_fee, dispatch_limit, payDesc });
      } if (code == FAIL) {
        const payDesc = payDescText(this.data.totalPrice, this.data.dispatch_limit);
        this.setData({ payDesc });
      }
    });
  },
  //清空回收站
  clearCart(e) {
    const token = getIn(getApp(), ['globalData', 'token']);
    const shop_id = getIn(this.options, ['shop_id']);
    global.ActionDispatcher.execute(cartEmptyQuery, { token, shop_id }, (code, res) => {
      if (code == SUCCESS) {
        this.fetchData(this.data.shop_detail);
        this.fetchCart(this.data.shop_detail);
        this.setData({ fold: false });
        showSuccess('操作成功');
      } else if (code == FAIL) {
        showFail('操作失败');
      }
    })
  },
  //修改产品购物车数量
  modifiesCart(e) {
    const { productObject, carArray } = this.data;
    const id = e.currentTarget.id || e.detail.id;
    const num = getIn(e.currentTarget.dataset, ['num']) || e.detail.num || 0;
    const oldnum = getIn(e.currentTarget.dataset, ['oldnum']) || e.detail.oldnum || 0;
    const token = getIn(getApp(), ['globalData', 'token']);
    const shop_id = getIn(this.options, ['shop_id']);
    const group_attr = getIn(e.detail, ['group_attr']);
    const callback = getIn(e.detail, ['callback']);
    const time = getIn(this.options, ['time']) && JSON.parse(getIn(this.options, ['time']));
    let params = { token, shop_id, product_id: id, num: Number(num) }
    if (time) {
      params = group_attr ? { ...params, group_attr, ...time } : { ...params, ...time };
    } else {
      params = group_attr ? { ...params, group_attr } : params;
    }
    this.setData({ 'productObject.num': Number(num) });
    global.ActionDispatcher.execute(getGoodsCartQuery, params, (code, res) => {
      if (code == SUCCESS) {
        const carArray = getIn(res.data, ['list']);
        const totalPrice = getIn(res.data, ['total_price']);
        const totalCount = getIn(res.data, ['total_num']);
        const payDesc = payDescText(totalPrice, this.data.dispatch_limit);
        if (totalCount == 0) {
          this.setData({ fold: false });
        }
        this.setData({ carArray, totalPrice, totalCount, payDesc });
      } else if (code == FAIL) {
        showFail(res.msg);
        if (Number(res.code) == -101) {
          this.setData({ 'productObject.num': 0 });
        } else {
          const reset_num = getIn(res.data, ['num']);
          this.setData({ 'productObject.num': Number(reset_num) });
        }
        
      }
    });
  },
  // 选择规格弹出窗
  selectAttr(e) {
    this.show('showAttr');
  },
  // 关闭属性框回调
  hideAttrBoxCallBack(e) {
    this.setData({ showAttr: e.detail.showAttr });
  },
  //结算
  pay() {
    if (this.data.totalPrice == 0 || this.data.totalPrice < this.data.dispatch_limit) {
      return;
    }
    const template = getIn(this.data, ['template']);
    const shop_id = getIn(this.options, ['shop_id']);
    const queryString = `color=${this.data.color}&shop_id=${shop_id}&template=${template}`;
    global.navigateHelper && global.navigateHelper.navigateTo({ pathname: CATERING_CREAT_ORDER, queryString });
  },
};
Page(pageConfig);
